package com.appspot.urlheap.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class BaseServlet extends HttpServlet {

	private Map<String, Object> values;
	private User                user;

	private void initValues(HttpServletRequest req) {
		UserService userService = UserServiceFactory.getUserService();
		user = userService.getCurrentUser();
		values = new HashMap<String, Object>();
		values.put("user", (user != null)? user.getNickname() : "anonymous");
		String url = ((HttpServletRequest) req).getRequestURL().toString();
		String query = ((HttpServletRequest) req).getQueryString();
		if (query != null && query.length() > 0) {
			url += "?" + query;
		}
		values.put("login", userService.createLoginURL(url));
		values.put("logout", userService.createLogoutURL("/index"));
        String host = req.getServerName();
        if (req.getServerPort() != 80) {
            host += ":" + req.getServerPort();
        }
		values.put("host", host);
	}

	Map<String, Object> getValues() {
		return values;
	}

	User getUser() {
		return user;
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html; charset=utf-8");
		initValues(req);
	}
}
